<?php

namespace App\Http\Controllers\Admin\System;

use App\Enums\ResponseEnum;
use App\Http\Controllers\AdminController;
use App\Models\System\User;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

class UserController extends AdminController
{
    public function data(Request $request)
    {
        $model = User::query()->select(['id', 'avatar', 'username', 'display_name', 'status', 'created_at', 'updated_at']);
        if ($keywords = $request->get('keywords')) {
            $keywords = filterStr($keywords);
            $model->where(function ($query) use ($keywords) {
                $query->where('username', 'like', $keywords.'%')->orWhere('display_name', 'like', $keywords.'%');
            });
        }
        $list = $model->with('roles:id')->paginate($request->get('limit', 10));
        $rows = $list->items();
        if (!empty($rows)) {
            foreach ($rows as $key => $row) {
                if (!empty($row['roles'])) {
                    $list[$key]['roles'] = Arr::pluck($row['roles'], 'id');
                }
            }
        }
        return $this->succeed([
            'total' => $list->total(),
            'rows'  => $rows,
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'username' => 'required|between:4,14|unique:users',
            'password' => 'required|between:8,16|regex:/^[A-Za-z\d-.]+$/|confirmed',
        ], [
            'username.between' => '用户名长度为4~14个字符',
            'username.unique' => '用户名已存在',
            'password.between' => '密码长度为8~16个字符',
            'password.regex' => '密码不允许有空格、中文',
        ]);
        $data = $request->only(['avatar', 'username', 'display_name', 'password', 'status']);
        try {
            DB::transaction(function () use ($data) {
                $user = User::query()->create([
                    'avatar' => $data['avatar'],
                    'username' => $data['username'],
                    'display_name' => $data['display_name'],
                    'password' => bcrypt($data['password']),
                    'status' => (int)$data['status'],
                    'uuid' =>  \Faker\Provider\Uuid::uuid(),
                ]);
                $this->createSyslog('添加管理员账号', $user);
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'username' => 'required|between:4,14|unique:users,username,'.$id.',id',
        ], [
            'username.between' => '用户名长度为4~14个字符',
            'username.unique' => '用户名已存在',
        ]);
        $user = User::query()->findOrFail($id);
        $data = $request->only(['avatar', 'username', 'display_name', 'status']);
        try {
            DB::transaction(function () use ($user, $data) {
                $user->update([
                    'avatar' => $data['avatar'],
                    'username' => $data['username'],
                    'display_name' => $data['display_name'],
                    'status' => (int)$data['status'],
                ]);
                $this->createSyslog('更新管理员账号', $user);
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }

    public function resetPassword(Request $request, $id)
    {
        $request->validate([
            'password' => 'required|between:8,16|regex:/^[A-Za-z\d-.]+$/'
        ], [
            'password.between' => '密码长度为8~16个字符',
            'password.regex' => '密码不允许有空格、中文',
        ]);
        $user = User::query()->findOrFail($id);
        $password = $request->get('password');
        try {
            DB::transaction(function () use ($user, $password) {
                $user->update(["password" => bcrypt($password)]);
                $this->createSyslog('重置管理员账号密码', $user);
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }

    public function assignRoles($id, Request $request)
    {
        $user = User::query()->findOrFail($id);
        $roles = $request->get('roles') ?? [];
        $user->syncRoles($roles);
        $this->createSyslog('更新管理员角色', $roles);
        return $this->succeed();
    }

    public function destroy(Request $request)
    {
        $request->validate(['ids' => 'required|array|size:'.static::QUERY_LIMIT]);
        $ids = $request->get('ids');
        abort_if(in_array(1, $ids, true), ResponseEnum::USER_EXISTS_DELETE_ERROR);
        $list = User::query()->select(['id'])->whereIn('id', $ids)->withCount('roles')->limit(static::QUERY_LIMIT)->get();
        abort_if($list->isEmpty(), ResponseEnum::DELETE_NOT_EXIST_ERROR);
        try {
            DB::transaction(function () use ($list) {
                foreach ($list as $model) {
                    abort_if($model->roles_count > 0, ResponseEnum::USER_EXISTS_ROLE_DELETE_ERROR);
                    $model->delete();
                    $this->createSyslog('删除管理员账号', $model);
                }
            });
            return $this->succeed();
        }catch (\Exception $e) {
            report($e);
        }
        return $this->error();
    }
}
